from pynput import mouse, keyboard
import json
import time

tips = input("[HoopyGame]:输入录制编号后开始录制，按ESC停止录制...")

# 存储记录的事件
events = []

# 记录按键的按下时间
key_press_times = {}

# 记录鼠标按钮的按下状态
mouse_pressed = False
mouse_button = None

# 标志位，用于控制是否停止录制
stop_recording = False

# 记录鼠标移动事件
def on_move(x, y):
    if not stop_recording:
        if mouse_pressed:
            # 如果鼠标按钮按下，记录为拖拽事件
            events.append({"type": "mouse_drag", "x": x, "y": y, "button": str(mouse_button), "time": time.time()})
        else:
            # 否则记录为普通移动事件
            events.append({"type": "mouse_move", "x": x, "y": y, "time": time.time()})

# 记录鼠标点击事件
def on_click(x, y, button, pressed):
    global mouse_pressed, mouse_button
    if not stop_recording:
        if pressed:
            # 记录鼠标按下事件
            mouse_pressed = True
            mouse_button = button
            events.append({"type": "mouse_press", "x": x, "y": y, "button": str(button), "time": time.time()})
        else:
            # 记录鼠标释放事件
            mouse_pressed = False
            events.append({"type": "mouse_release", "x": x, "y": y, "button": str(button), "time": time.time()})

# 记录键盘按下事件
def on_press(key):
    global stop_recording
    if not stop_recording:
        try:
            # 普通按键
            key_char = key.char
        except AttributeError:
            # 特殊按键
            key_char = str(key)
        # 记录按键按下的时间
        key_press_times[key_char] = time.time()

        # 如果按下 Esc 键，停止录制
        if key == keyboard.Key.esc:
            stop_recording = True
            return False  # 停止监听

# 记录键盘释放事件
def on_release(key):
    if not stop_recording:
        try:
            # 普通按键
            key_char = key.char
        except AttributeError:
            # 特殊按键
            key_char = str(key)
        # 计算按键按下的持续时间
        if key_char in key_press_times:
            press_time = key_press_times[key_char]
            duration = time.time() - press_time
            events.append({"type": "key_press", "key": key_char, "duration": duration, "time": press_time})
            # 删除已记录的按下时间
            del key_press_times[key_char]

# 启动监听
mouse_listener = mouse.Listener(on_move=on_move, on_click=on_click)
keyboard_listener = keyboard.Listener(on_press=on_press, on_release=on_release)

mouse_listener.start()
keyboard_listener.start()

# 监听直到按下 Esc 键
print("开始录制，按下 Esc 键停止录制...")
keyboard_listener.join()  # 等待键盘监听器停止

# 停止鼠标监听器
mouse_listener.stop()

# 保存记录到文件
with open("./"+tips+".json", "w") as f:
    json.dump(events, f)

print("录制已停止，操作已记录")